<template>
  
  <div style="margin: 10px" v-if="act===null">
    <van-skeleton title avatar :row="3" />
  </div>
  
  
  <div v-else>
    <div class="act-info-container-div">
      <ActInfoHead
        :user="user"
        :act="act"
        :apply="apply"
        />
      <div class="act-info-text-container-div">
        <ActTitle
            :title="act.title"
        />
        <ActCats
            :cats="act.cats"
        />
        <div>
          <van-text-ellipsis
              rows="8"
              :content="act.info"
              expand-text="展开"
              collapse-text="收起"
          />
        </div>
        
        <ActTime
          :time1="act.startTime"
          :time2="act.endTime"
          />
        <ActPlaceSize
          :place="act.place"
          :size="act.size"
          :apply-num="act.applyNum"
          />
        <ShowImg :img-list="act.imgs"/>
      </div>
      
<!--      操作按钮组-->
      <div class="button-bar-div">
<!--        自己发布的活动-->
        <div v-show="isSelf">
          <span v-if="act.publish">
            <el-button type="warning" @click="cancelPublish">取消发布</el-button>
            <el-button @click="gotoSta">统计信息</el-button>
            <el-button type="success" @click="signAct">发起签到</el-button>
          </span>
          <span v-else>
            <el-button type="primary" @click="publishAct">发布活动</el-button>
            <el-button type="info" @click="updateAct">修改活动</el-button>
            <el-button type="danger" @click="delAct">删除活动</el-button>
          </span>
        </div>
<!--        已报名活动-->
        <div v-show="isApply">
          <el-button type="warning" round @click="cancelApply">取消报名</el-button>
        </div>
        
        <div v-show="!isSelf && !isApply && showApplyButton" style="width: 100%">
          <van-button round type="primary" plain size="large" @click="getQn">报名活动</van-button>
        </div>
      </div>
      
<!--      问卷展示区-->
      <div v-if="qn.length > 0">
        <QNList
          :qn="qn"
          :user="user"
          :show="isSelf || isApply"
          :apply="!showApplyButton"
          :sta="act.publish"
          @sta="gotoQSta"
          />
        <div v-if="!showApplyButton" style="margin: 5px 10px">
          <van-button type="primary" round size="large" @click="submitApply">报名活动</van-button>
        </div>
      </div>
    </div>
  </div>
  
  <van-dialog
      v-model:show="dialog.show"
      :title="dialog.title"
      @close="closeDialog">
    <div class="qrcode-dialog-div">
      <div>
        <el-button @click="copyUrl">复制网址</el-button>
      </div>
      <div class="url-div">{{dialog.url}}</div>
      
      <div class="warning-div">二维码，请注意保存</div>
      <img :src="dialog.qrcode"/>
    </div>
  </van-dialog>
  
</template>

<script>
import {defineComponent} from 'vue'
import actApi from "@/utils/api/actApi";
import UserAvatarName from "@/components/UserAvatarName.vue";
import ActTitle from "@/views/act/components/ActTitle.vue";
import ActCats from "@/views/act/components/ActCats.vue";
import ActTime from "@/views/act/components/ActTime.vue";
import ActPlaceSize from "@/views/act/components/ActPlaceSize.vue";
import ActInfoHead from "@/views/act/components/ActInfoHead.vue";
import {closeToast, showConfirmDialog, showFailToast, showLoadingToast, showSuccessToast, showToast} from "vant";
import commonUtil from "@/utils/commonUtil";
import QNList from "@/views/act/components/QNList.vue";
import DBConst from "@/consts/DBConst";
import ShowImg from "@/components/ShowImg.vue";

export default defineComponent({
  name: "ActInfo",
  components: {ShowImg, QNList, ActInfoHead, ActPlaceSize, ActTime, ActCats, ActTitle, UserAvatarName},
  created() {
    let actId = this.$route.query.actId
    if(actId){
      this.init(actId)
    }
  },
  data(){
    return {
      act: null,
      user: null,
      qn: null,
      apply: null,
      dialog: {
        show: false,
        title: '',
        url: '',
        qrcode: ''
      },
      showApplyButton: true,
      signFlag: false
    }
  },
  methods: {
    gotoQSta(qId){
      this.$router.push({
        path: '/act/apply/q',
        query: {
          actId: this.act.actId,
          qId
        }
      })
    },
    gotoSta(){
      this.$router.push({
        path: '/act/apply',
        query: {actId: this.act.actId}
      })
    },
    async init(actId){
      let data = await actApi.getActInfo(actId)
      this.act = data.act
      this.user = data.user
      this.qn = data.qn
      this.apply = data.apply
    },
    async publishAct(){
      try {
        showLoadingToast({
          message: '活动发布中...',
          forbidClick: true,
          duration: 0
        });
        let {url, qrcode} = await actApi.publishAct(this.act.actId)
        closeToast(true)
        this.openDialog('活动链接与二维码',url, qrcode)
      }catch (data){
      
      }finally {
      
      }
    },
    updateAct(){
      this.$router.replace({
        path: '/act/edit',
        query: {actId: this.act.actId}
      })
    },
    cancelPublish(){
      showConfirmDialog({
        title: '取消活动',
        message:
            '是否确认取消活动？\n活动一旦取消之前的所有报名记录将会清空',
      })
          .then(async () => {
            try {
              showLoadingToast({
                message: '活动取消中...',
                forbidClick: true,
                duration: 0
              });
              await actApi.cancelPublishAct(this.act.actId)
              showToast("活动已取消")
              this.$router.go(0)
            }catch (data){
            
            }finally {
            
            }
          })
          .catch(() => {
            // on cancel
          });
    },
    delAct(){
      showConfirmDialog({
        title: '删除活动',
        message:
            '是否确认删除活动？\n活动一旦删除不可恢复',
      })
          .then(async () => {
            try {
              showLoadingToast({
                message: '活动删除中...',
                forbidClick: true,
                duration: 0
              });
              await actApi.deleteAct(this.act.actId)
              showToast("活动已删除")
              this.$router.go(-1)
            }catch (data){
            
            }finally {
            
            }
          })
          .catch(() => {
            // on cancel
          });
    },
    async signAct(){
      try {
        showLoadingToast({
          message: '请求中...',
          forbidClick: true,
          duration: 0
        });
        let {url, qrcode} = await actApi.signQrcode(this.act.actId)
        closeToast(true)
        this.signFlag = true
        this.openDialog('活动签到链接与二维码',url, qrcode)
      }catch (data){
      
      }finally {
      
      }
    },
    cancelApply(){
      showConfirmDialog({
        title: '取消报名',
        message:
            '是否确认取消报名该活动？',
      })
          .then(async () => {
            try {
              showLoadingToast({
                message: '取消报名中...',
                forbidClick: true,
                duration: 0
              });
              await actApi.cancelApplyAct(this.apply.applyId)
              showToast("已取消报名活动")
              this.$router.go(0)
            }catch (data){
            
            }finally {
            
            }
          })
          .catch(() => {
            // on cancel
          });
    },
    async getQn(){
      try {
        showLoadingToast({
          message: '加载中...',
          forbidClick: true,
          duration: 0
        });
        let qn = await actApi.getActQn(this.act.actId)
        this.qn = qn
        closeToast(true)
        if(qn.length === 0){
          this.submitApply()
        }else {
          showToast("请填写活动问卷")
          this.showApplyButton = false
        }
      }catch (data){
      
      }finally {
      
      }
    },
    async submitApply(){
      let {qn, flag} = this.checkQnAns()
      if(!flag){
        showToast("请完成所有问卷题目")
        return
      }
      showConfirmDialog({
        title: '确认报名',
        message:
            '是否确认报名该活动？',
      }).then(async ()=>{
        try {
          showLoadingToast({
            message: '提交中...',
            forbidClick: true,
            duration: 0
          });
          await actApi.applyAct(this.act.actId, qn)
          showSuccessToast('提交成功')
          this.$router.go(0)
        }catch (data){
        
        }finally {
        
        }
      }).catch(()=>{})
      
      
    },
    checkQnAns(){
      let flag = true
      //map成qn参数并且所有题目是否填写
      let qn = this.qn.map(item=>{
        let q = {qId: item.qId}
        switch (item.type){
          case DBConst.QType.MULTI: {
            //多选题，ans是数组
            if(item.ans.length === 0){
              //多选题未选
              flag = false
            }else {
              //多选题选了
              q.ans = item.ans.sort((a,b)=>a-b).join(',')
            }
            break
          }
          case DBConst.QType.SINGLE: {
            //单选题
            if(item.ans === null){
              flag = false
            }else {
              q.ans = item.ans
            }
            break
          }
          case DBConst.QType.BLANK: {
            //填空题
            if(item.ans !== null){
              item.ans = item.ans.trim()
              if(item.ans !== ''){
                q.ans = item.ans
              }else {
                flag = false
              }
            }else {
              flag = false
            }
            break
          }
        }
        return q
      })
      
      return {qn, flag}
    },
    openDialog(title, url, qrcode){
      this.dialog.title = title
      this.dialog.url = url
      this.dialog.qrcode = qrcode
      this.dialog.show = true
    },
    closeDialog(){
      if(this.signFlag){
        this.signFlag = false
      }else {
        this.$router.go(0)
      }
    },
    copyUrl(){
      try {
        commonUtil.copyToClipboard(this.dialog.url)
        showSuccessToast("复制成功")
      }catch (e){
        showFailToast("复制失败")
      }
    }
  },
  computed: {
    isSelf(){
      return this.user.self
    },
    isApply(){
      return this.apply !== null
    }
  }
})
</script>



<style scoped lang="less">
.act-info-container-div {
  display: flex;
  flex-direction: column;
  margin: 5px 10px;
  >.act-info-text-container-div{
    display: flex;
    flex-direction: column;
    margin: 5px 5px;
    >div{
      margin-bottom: 8px;
    }
  }
}

.button-bar-div {
  display: flex;
  justify-content: space-around;
}

.qrcode-dialog-div {
  display: flex;
  flex-direction: column;
  padding: 10px;
  >.url-div{
    font-size: 14px;
    color: #007bff;
    margin: 5px;
  }
  >.warning-div{
    color: red;
  }
}
</style>